package com.huohuo.concurrent.zk;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

public class ZkDistrbuteLock extends ZkAbstractLock {

    private static CountDownLatch countDownLatch = null;

    @Override
    boolean tryLock() {
        try {
            //使用继承类中的实例对象
            zkClient.createEphemeral( path1 );
            return true;

        } catch (Exception e) {
            return false;

        }
    }


    /**
     * waitiLock中创建一个节点，监听上一个节点是否删除了，删除了新创建的节点才有可能获得锁
     */
    @Override
    void waitLock() {
        //创建监听
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                //如果上一个节点删除了，唤醒被等待的线程
                if (countDownLatch !=null){
                    countDownLatch.countDown();//节点减1
                }
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        };
        //注册事件
        zkClient.subscribeDataChanges( path1,listener );

        // countDownLatch.countDown()减1之后判断节点是否存在
        if(zkClient.exists( path1 )){
            countDownLatch = new CountDownLatch( 1 );
            try {
                countDownLatch.wait();

            }catch (Exception e){
                //这里不打印异常，就是利用这里的异常新节点才能获取异常
              //  e.printStackTrace();
            }
        }
        //删除监听
        zkClient.unsubscribeDataChanges( path1,listener );
    }

    @Override
    public void unLock() {
        if (zkClient!=null ){
            zkClient.delete( path1 );
            zkClient.close();
            System.out.println("最后释放锁资源");
        }

    }
}
